package tech.tuister.cninfo.download.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import tech.tuister.cninfo.download.util.CninfoAPI;
import tech.tuister.cninfo.download.util.Stocks;
import tech.tuister.cninfo.download.util.Stocks.Stock;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@CninfoAPI
public class AnnouncementQueryAPI {
    public static final String BASE_DIR = "D:\\BaiduSyncdisk\\企业财报\\";

    static final String URL = "http://www.cninfo.com.cn/new/hisAnnouncement/query";

    public static void download(String stockCode) throws Exception {

        Stock stock = Stocks.findStockByCode(stockCode);

        HttpPost request = new HttpPost(URL);
        Map<String, Object> params = new HashMap<>();

        params.put("stock", stockCode + "," + stock.getOrgId());
        params.put("column", "szse");
        // params.put("plate", plate);

        //以下都是常量
        params.put("tabName", "fulltext");
        params.put("pageSize", 30);
        params.put("pageNum", 1);
        params.put("category", "category_ndbg_szsh;category_bndbg_szsh;category_yjdbg_szsh;category_sjdbg_szsh;");
        params.put("seDate", "");
        params.put("searchkey", "");
        params.put("secid", "");
        params.put("sortName", "");
        params.put("sortType", "");
        params.put("isHLtitle", "true");


        List<BasicNameValuePair> pairs = params.entrySet().stream()
                .map(e -> new BasicNameValuePair(e.getKey(), e.getValue().toString()))
                .collect(Collectors.toList());
        request.setEntity(new UrlEncodedFormEntity(pairs));

        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(HttpHeaders.ACCEPT, "application/json, text/javascript, */*; q=0.01"));
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"));
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"));
        headers.add(new BasicHeader(HttpHeaders.CONNECTION, "keep-alive"));
        headers.add(new BasicHeader(HttpHeaders.REFERER, "http://www.cninfo.com.cn/"));
        headers.add(new BasicHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.78"));
        request.addHeader(new BasicHeader("X-Requested-With", "XMLHttpRequest"));

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultHeaders(headers)
                .build();

        CloseableHttpResponse response = httpClient.execute(request);
        String content = EntityUtils.toString(response.getEntity());

        JSONObject jsonObject = JSON.parseObject(content);
        JSONArray announcements = jsonObject.getJSONArray("announcements");

        System.out.println("Find announcements: " + announcements.size());


        String stockSavePath = BASE_DIR + stock.getZwjc();

        if (!new File(stockSavePath).exists()) {
            System.out.println(stockSavePath + ": " + new File(stockSavePath).mkdirs());
        }
        for (Object announcement : announcements) {

            System.out.println(JSON.toJSONString(announcement, JSONWriter.Feature.PrettyFormat));

            String adjunctUrl = ((JSONObject) announcement).getString("adjunctUrl");

            String announcementTitle = ((JSONObject) announcement).getString("announcementTitle");

            try (InputStream stream = new URL("http://static.cninfo.com.cn/" + adjunctUrl).openStream()) {
                Path savePath = Paths.get(stockSavePath + "\\" + announcementTitle + ".pdf");
                if (Files.exists(savePath)) {
                    log.info("{} exist, skip", savePath);
                    continue;
                }

                Files.copy(stream, savePath);
                long length = savePath.toFile().length();
                System.out.println("saved, length is " + length);
            }


            try {
                long time = System.currentTimeMillis() % 3;
                TimeUnit.SECONDS.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        response.close();

        httpClient.close();
    }
}
